#!/data/Software/mydan/perl/bin/perl -I/data/Software/mydan/CI/lib -I/data/Software/mydan/CI/private/lib
use strict;
use warnings;
use POSIX;
use Logs;
use FindBin qw( $RealBin );
use Temp;
use MIME::Base64;
use File::Basename;
use Code;
use LWP::UserAgent;
use Encode;
use Util;
use JSON;

$| ++;

=head1 SYNOPSIS

    db => $mysql,
    logs => 日志对象

    # projectid addr ticketid rely name(版本信息可能为空) temp(logs目录下的临时目录名) uuid

=cut

return sub
{
    my %param = @_;

    my ( $db, $logs, $projectid, $addr, $ticketid, $rely, $name, $temp, $uuid, $treeid )
        = @param{qw(db logs projectid addr ticketid rely name temp uuid treeid )};

    $logs = Logs->new( 'code.build.dump.pull.openc3fileserver' ) unless $logs;

    my $temppath = "$RealBin/../logs/$temp/$uuid";
    if( -d $temppath )
    {
        my $user = `id -un`;chop $user;
        my $sudo = $user eq 'root' ? '' : 'sudo ';
        $logs->die( "clean old temppath fail:$!" ) if system "${sudo}rm -rf '$temppath'";
    }

    $logs->die( "mkdir temppath fail:$!" ) if system "mkdir -p '$temppath'";

    my $ua = LWP::UserAgent->new();
    $ua->agent('Mozilla/9 [en] (Centos; Linux)');
    $ua->default_header( Util::envinfo( qw( appkey appname ) ) );
    $ua->timeout( 10 );
    my $res = $ua->get( "http://api.job.open-c3.org/fileserver/$treeid" );
    my $cont = $res->content;
    $logs->die( "calljob fail: $cont" ) unless $res->is_success;

    my $data = eval{JSON::from_json $cont};
    $logs->die( "calljob fail: $cont : no json $@" ) if $@;

    $logs->die( "calljob fail: $cont : stat fail" ) unless $data->{stat};

    my $tagdata;
    if( $name )
    {
        map{ $tagdata = $_ if $_->{name} eq $name }@{$data->{data}};
    }
    else
    {
        $data = pop @{$data->{data}};
    }

    $logs->die( "nofind version" ) unless $tagdata;

    my $filepath = "/data/glusterfs/fileserver/$treeid/$tagdata->{md5}";
    $name = $tagdata->{name};
    print "version: $name\n";

    $logs->die( "name format error" ) unless $name =~ /^[a-zA-Z0-9\.\-_]+$/;
    $logs->die( "clone error:$!" ) if system "cd '$temppath' && rm -rf data info && mkdir data && mkdir info && tar -zxvf '$filepath' -C data && echo '$name' > info/version";

    my $tagger = $tagdata->{create_user};
    unless( defined $tagger && $tagger =~ /^[a-zA-Z0-9\.\@\-_]+$/ )
    {
        print "get tagger fail,Switch to default: open-c3\@org\n";
        $tagger = 'open-c3@org';
    }

    print "tagger: $tagger\n";
    $logs->die( "write tagger info fail:$!" )if system "echo '$tagger' > '$temppath/info/tagger'";
    $logs->die( "write taginfo info fail:$!" )if system "echo '${tagger}_${name}' > '$temppath/info/taginfo'";
}
